import constant from '../../constant';
import storage from '../../utils/storage'
import service from '../../service'
import { isArray } from '../../utils/util'
import { getTree, parents, recursion } from '../../utils/tree';
import router, {resetRouter, parseRouters} from '../../router';

const state = {
    routes: storage.getOrDefault(constant.STORAGE.MENU.VIEW_ROUTES, []),
    group: storage.getOrDefault(constant.STORAGE.MENU.MENU_GROUP, []),
    menu: [],
    permission: [],
    collapse: storage.getOrDefault(constant.STORAGE.MENU.COLLAPSE, !1),
    topbar: {}
}

const actions = {
    permMenu({commit, dispatch}) {
        return new Promise(((resolve, reject) => {
            service.common.permMenu().then((res) => {
                isArray(res.menus) ||  (console.warn("Invalid menus. Expected Array"), n.menus = [])
                isArray(res.perms) ||  (console.warn("Invalid menus. Expected Array"), n.menus = [])
                let menus = res.menus
                    .filter(e=> 2!== e.type)
                    .map((e) => {
                        return {
                            id: e.id,
                            parentId: e.parentId,
                            path: e.router || `/${e.id}`,
                            viewPath: e.viewPath,
                            type: e.type,
                            name: e.name,
                            icon: e.icon,
                            orderNum: e.orderNum,
                            meta: {
                                title: e.name,
                                keepAlive: e.keepAlive,
                                iframeUrl: e.viewPath ? (e.viewPath.indexOf('http') !== -1 ? e.viewPath : null) : null
                            },
                            children: []
                        }
                    });
                let menuGroup = getTree(menus, (item, parent, children) => {
                    children.push(item);
                }, 'id', 'parentId', ['orderNum'])
                let viewRoutes = menus.filter((e) => 1 === e.type)
                commit("SET_PERMIESSION", res.perms)
                commit("SET_MENU_GROUP", menuGroup)
                commit("SET_VIEW_ROUTES", viewRoutes)
                // 加载动态路由
                resetRouter()
                router.addRoutes(parseRouters(viewRoutes))
                // 根据当前url默认选中顶部菜单栏
                if (menuGroup && menuGroup.length > 0) {
                    // 加载顶部菜单栏
                    let topbarMenuId = menuGroup[0].id  // 顶部菜单栏默认选中菜单
                    // 读取当前路径
                    let currentPath = location.hash.substring(1)
                    let currentMenu = recursion(menuGroup, currentPath, 'path')
                    if (currentMenu) {
                        // 获取当前路径所在父菜单
                        let parentMenus = parents(menuGroup, currentMenu.id, 'parentId')
                        topbarMenuId = parentMenus.length > 0 ? parentMenus[parentMenus.length - 1].id : topbarMenuId
                    }
                    // 选中顶部菜单
                    dispatch('topbarMenu', {
                        id: topbarMenuId,
                        open: false
                    })
                }
                resolve(menuGroup);
            })
        }))
    },
    // 选择顶部菜单栏
    topbarMenu({ commit }, topbarMenu) {
        return new Promise(((resolve, reject) => {
            // 先查找出当前所在父级菜单
            let ps = state.group.filter(p=>p.id === topbarMenu.id)
            let topbar = !ps || ps[0]
            // 判断顶部菜单类型
            switch (topbar.type) {
                case 0:
                    // 目录
                    commit('SET_MENU_LIST', topbar)
                    break;
                case 1:
                    // 菜单
                    commit('SET_MENU_LIST', topbar)
                    if (topbarMenu.open) {
                        router.push(topbar.path)
                    }
                    break;
            }
            resolve();
        }))
    }
}

const mutations = {
    SET_MENU_GROUP(state, menuGroup) {
        state.group = menuGroup
        storage.set(constant.STORAGE.MENU.MENU_GROUP, menuGroup)
    },
    SET_VIEW_ROUTES(state, viewRoutes) {
        state.routes = viewRoutes
        storage.set(constant.STORAGE.MENU.VIEW_ROUTES, viewRoutes)
    },
    SET_MENU_LIST(state, topbar) {
        state.topbar = topbar
        state.menu = topbar ? topbar.children: []
    },
    SET_PERMIESSION(state, perms) {
        state.permission = perms
    },
    COLLAPSE_MENU(state) {
        state.collapse = !state.collapse
        storage.set(constant.STORAGE.MENU.COLLAPSE, state.collapse)
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
